<?php
class CConsultUser
{
	var $LAST_ERROR ="";

	function GetDeniedRoleID()
	{
		return "D";
	}

	function GetConsultClientRoleID()
	{
		return "R";
	}

	function GetConsultTeamRoleID()
	{
		return "T";
	}

	function GetAdminRoleID()
	{
		return "W";
	}
	
	// true - если пользователь имеет роль "администратор техподдержки"
	// false - в противном случае
	function IsAdmin($USER_ID=false)
	{
		global $USER;
		if ($USER_ID===false && is_object($USER))
		{
			if ($USER->IsAdmin()) return true;
		}
		return CConsultUser::HaveRole(CConsultUser::GetAdminRoleID(), $USER_ID);
	}
	
	// true - если пользователь имеет роль "сотрудник техподдержки"
	// false - в противном случае
	function IsConsultTeam($USER_ID=false)
	{
		return CConsultUser::HaveRole(CConsultUser::GetConsultTeamRoleID(), $USER_ID);
	}
	
	function IsConsultClient($USER_ID=false)
	{
		return CConsultUser::HaveRole(CConsultUser::GetConsultClientRoleID(), $USER_ID);
	}
	
	function HaveRole($role, $USER_ID=false)
 	{
		global $DB, $USER, $APPLICATION, $CONSULT_CACHE_USER_ROLES;

		if (!is_array($CONSULT_CACHE_USER_ROLES))
			$CONSULT_CACHE_USER_ROLES = array();

		if (!is_object($USER)) $USER = new CUser;

 		if ($USER_ID===false && is_object($USER))
			$UID = $USER->GetID();
		else
			$UID = $USER_ID;

		$arRoles = Array();

		if (array_key_exists($UID, $CONSULT_CACHE_USER_ROLES) && is_array($CONSULT_CACHE_USER_ROLES[$UID]))
		{
			$arRoles = $CONSULT_CACHE_USER_ROLES[$UID];
		}
		else
		{
			$arrGroups = Array();
			if ($USER_ID===false && is_object($USER))
				$arrGroups = $USER->GetUserGroupArray();
			else
				$arrGroups = CUser::GetUserGroup($USER_ID);

			sort($arrGroups);
			$arRoles = $APPLICATION->GetUserRoles("consult", $arrGroups);
			$CONSULT_CACHE_USER_ROLES[$UID] = $arRoles;
		}

		if (in_array($role, $arRoles))
			return true;

		return false;
	}
	
	function GetCurConsultUser ($return_array = false)
	{
		global $USER, $APPLICATION;
		if ($return_array === false && $_SESSION["CONS_USER_ID"] && intval ($_SESSION["CONS_USER_ID"])>0)
		{
			return  $_SESSION["CONS_USER_ID"];
		}

		$bAuth = $USER->IsAuthorized();
		if ($bAuth)
		{
			$arFilter = array("ENTITY_TYPE"=> "U", "ENTITY_ID" => $USER->GetID());
		}
		else
		{
			$hash = $APPLICATION->get_cookie("CONSULT_USER_SID");
			if ($hash === "")
				return false;
			else
				$arFilter = array("ENTITY_TYPE"=> "G", "ENTITY_ID" =>$hash);
		}
		$dbUser = CConsultUser::GetList (array(), $arFilter);

		if ($arCurUser = $dbUser->Fetch())  //Получили текущего пользователя.
		{
			if ($return_array)
				return $arCurUser;
			else
				return $arCurUser["ID"];
		}
		else
			return false;
	}

	function SetLastActivityDate($id)
	{
		global $DB;

		$id = IntVal($id);
		if ($id <= 0)
			return;

		$DB->Query("UPDATE b_consult_user SET ".
			"LAST_ACTIVITY = ".$DB->CurrentTimeFunction()." WHERE ID = ".$id.""
			, false, "", array("ignore_dml"=>true));
	}

	function GetUserPhotoHtml ($photo_id, $arSize, $defaultImage="/bitrix/images/consult/nopic_30x30.gif", $imageParams="")
	{
		$imageImg = "";
		$imageParams .= " border=0";
		$imageFile = CFile::GetFileArray($photo_id);
		if ($imageFile !== false)
		{
			if (!is_array($arSize))
			{
				$arSize = array();
				$arSize["X"] = 50; $arSize["Y"] = 50;	
			}

			$arFileTmp = CFile::ResizeImageGet(
				$imageFile,
				array("width" => $arSize["X"], "height" => $arSize["Y"]),
				BX_RESIZE_IMAGE_PROPORTIONAL,
				false
				);
			$imageImg = CFile::ShowImage($arFileTmp["src"], $arSize["X"], $arSize["Y"], $imageParams , "");
			return $imageImg;
		}
		if ($imageImg == "")
		{
			$imageImg = "<img src=\"$defaultImage\" width=\"".$arSize["X"]."\" height=\"".$arSize["Y"]."\" $imageParams>";
			return $imageImg;
		}

		return false;
	}

	function GetByID($ID)
	{
		global $DB;
		$ID = intval($ID);
		if ($ID <= 0)
			return false;

		$strSql = 	"SELECT CU.ID, CU.NAME, CU.ENTITY_TYPE, CU.ENTITY_ID, CU.PHOTO, 
						".$DB->DateToCharFunction("CU.DATE_CREATE", "FULL")." as DATE_CREATE,
						".$DB->DateToCharFunction("CU.LAST_ACTIVITY", "FULL")." as LAST_ACTIVITY 
					FROM b_consult_user CU ".
					"WHERE CU.ID='".$ID."'";

		$res = $DB->Query($strSql);
		if($arUser = $res->Fetch())
			return $arUser;

		return false;
	}
	function GetList($arOrder = array(), $arFilter = array())
	{
		global $DB;

		$arSqlOrder = array();
		$strSqlOrder = "";

		static $arFields = array(
			"ID" => 		Array("FIELD_NAME" => "CU.ID", 			"FIELD_TYPE" => "int"),
			"NAME" => 		Array("FIELD_NAME" => "CU.NAME", 		"FIELD_TYPE" => "string"),
			"ENTITY_TYPE" => Array("FIELD_NAME" => "CU.ENTITY_TYPE", "FIELD_TYPE" => "string"),
			"ENTITY_ID" => 	Array("FIELD_NAME" => "CU.ENTITY_ID", 	"FIELD_TYPE" => "string"),
			"DATE_CREATE" => Array("FIELD_NAME" => "CU.DATE_CREATE", "FIELD_TYPE" => "datetime"),
			"LAST_ACTIVITY" => Array("FIELD_NAME" => "CU.LAST_ACTIVITY", "FIELD_TYPE" => "datetime"),
		);

		$obWhere = new CSQLWhere;
 		$obWhere->SetFields($arFields);
 		$arFilterNew = Array();

		foreach($arFilter as $k=>$value)
			if(strlen($value)>0 || $value === false)
				$arFilterNew[$k]=$value;

		$strWhere = $obWhere->GetQuery($arFilterNew);


		foreach ($arOrder as $by=>$order)
		{
		
			$by = strtoupper($by); 
			$order = strtoupper($order);

			if ($order!="ASC") $order = "DESC";

			if ($by == "NAME") $arSqlOrder[] = " CU.NAME ".$order." ";
			elseif ($by == "ENTITY_TYPE") $arSqlOrder[] = " CU.ENTITY_TYPE ".$order." ";
			elseif ($by == "ENTITY_ID") $arSqlOrder[] = " CU.ENTITY_ID ".$order." ";
			elseif ($by == "DATE_CREATE") $arSqlOrder[] = " CU.DATE_CREATE ".$order." ";
			elseif ($by == "LAST_ACTIVITY") $arSqlOrder[] = " CU.LAST_ACTIVITY ".$order." ";
			else
			{
				$arSqlOrder[] = " CU.ID ".$order." ";
				$by = "ID";
			}
		}

		$arSqlOrder = array_unique($arSqlOrder);
		DelDuplicateSort($arSqlOrder);
		if(count($arSqlOrder) > 0)
			$strSqlOrder = " ORDER BY ".implode(", ", $arSqlOrder);

		$strSql = "
			SELECT
				CU.ID, CU.NAME, CU.ENTITY_TYPE, CU.ENTITY_ID, 
				".$DB->DateToCharFunction("CU.DATE_CREATE", "FULL")." as DATE_CREATE,
				".$DB->DateToCharFunction("CU.LAST_ACTIVITY", "FULL")." as LAST_ACTIVITY 
			FROM
				b_consult_user CU ".
			(strlen($strWhere)<=0 ? "" : "WHERE ".$strWhere)." ".
			$strSqlOrder;

		//var_dump($strSql);

		$res = $DB->Query($strSql, false, "FILE: ".__FILE__."<br> LINE: ".__LINE__);
	
		return $res;
	}
	
	function Add ($arFields)
	{
		global $DB, $USER, $APPLICATION;

		$this->LAST_ERROR = "";
		$this->METHOD = "CConsultUser::Add(".__LINE__.")";

		if (!$this->CheckFields($arFields))
			return false;

		$dbInsert = array(
			"~DATE_CREATE" => (isset($arFields ["DATE_CREATE"])? $arFields ["DATE_CREATE"] : $DB->GetNowFunction()),
			"ENTITY_TYPE" => $arFields["ENTITY_TYPE"],
			"ENTITY_ID" => $arFields["ENTITY_ID"],
			"NAME" => $arFields["NAME"],
		);

		if (isset ($arFields["LAST_ACTIVITY"]))
			$dbInsert["LAST_ACTIVITY"] = $arFields["LAST_ACTIVITY"];

		//Check exists user
		$strSql = 	"SELECT 'x'
					FROM b_consult_user
					WHERE ENTITY_TYPE = '".$DB->ForSQL ($dbInsert["ENTITY_TYPE"], 1)."' AND ENTITY_ID = '".$DB->ForSQL ($dbInsert["ENTITY_ID"], 32)."'";

		$res = $DB->Query($strSql);
		if ($res->Fetch())
		{
			$this->LAST_ERROR .= "User already exists<br>";
			return false;
		}
		//END Check exists user
		$arInsert = $DB->PrepareInsert("b_consult_user", $dbInsert);
		$strSqlInsert =	"INSERT INTO b_consult_user(".$arInsert[0].") ".
				"VALUES(".$arInsert[1].")";

		if ($DB->Query($strSqlInsert))
		{
			if (($arFields["ENTITY_TYPE"] != "U"))
				$APPLICATION->set_cookie("CONSULT_USER_SID", $arFields["ENTITY_ID"], time()+60*60*24*30, "/");

			$ID = $DB->LastID();

			$_SESSION["CONS_USER_ID"] = $ID;
			return $ID;
		}

		return false;

	}

	function CheckFields ($arFields, $ID = false)
	{
		if (!is_array($arFields))
			return false;

		if ($ID === false)
		{
			if (!isset($arFields["ENTITY_TYPE"]) || !isset($arFields["ENTITY_ID"]))

				$this->LAST_ERROR .= "ENTITY_TYPE or ENTITY_ID can't be empty"."<br>";
		}
		if (isset($arFields["ENTITY_ID"]) && $arFields["ENTITY_TYPE"] == "U")
		{
			if (intval($arFields["ENTITY_ID"]) > 0)
			{
				$arResp = CUser::GetByID($arFields["ENTITY_ID"]);
				if (!$arResp->Fetch())
					$this->LAST_ERROR .= "ENTITY_ID contain not ID of user"."<br>";
			}
			else
			{
				$this->LAST_ERROR .= "ENTITY_ID contain incorrect value"."<br>";
			}
		}

		if (isset ($arFields["DATE_CREATE"]) && !CheckDateTime($arFields["DATE_CREATE"]))
			$this->LAST_ERROR .= "DATE_CREATE contain incorrect value"."<br>";

		if (isset ($arFields["LAST_ACTIVITY"]) && !CheckDateTime($arFields["LAST_ACTIVITY"]))
			$this->LAST_ERROR .= "LAST_ACTIVITY contain incorrect value"."<br>";

		if(strlen($this->LAST_ERROR)>0)
			return false;

		return true;
	}
	function Update($ID, $arFields)
	{
		global $DB;
		$this->LAST_ERROR = ""; 
		$this->METHOD = "CConsultUser::Update(".__LINE__.")";

		$ID = intval($ID);
		
		if(!$this->CheckFields($arFields, $ID))
			return false;

		unset ($arFields["DATE_CREATE"]);
		unset ($arFields["ID"]);

		$strUpdate = $DB->PrepareUpdate("b_consult_user", $arFields);
		$strSql = "UPDATE b_consult_user SET ".$strUpdate." WHERE ID=".$ID;
		//echo "<pre>".$strSql."</pre>";
		$DBres = $DB->Query($strSql, false, "FILE: ".__FILE__."<br> LINE: ".__LINE__);

		if ($DBres) 
			return  true;
			
		return false;
	}
	function Delete ($ID)
	{
		global $DB, $USER;
		$ID = intval($ID);
		if ($ID <= 0)
			return false;

		$strSql = "DELETE FROM b_consult_user ".
						"WHERE ID='".$ID."'";
		$res = $DB->Query($strSql);
		if ($res)
			return true;

		return false;
	}
}
?>
